/**
 * Created by hjqi on 2016/6/02.
 */
module.controller('StorageDetailController',
    function ($scope,$cookies,$stateParams,$uibModal,storageService) {

        $scope.volumnName = $stateParams.volId;
        $scope.files = [];
        var user = $cookies.get("username");

        var loadData = function () {
            storageService.getFilesFromStorageName($scope.volumnName).then(function(rets){
                $scope.files = rets.data.slice();
            },function(err){
                alertify.error(err);
            });
        }

        loadData();

        $scope.$watchCollection('files', function (newvalue,oldvalue) {
            $scope.fileslist = newvalue.slice();
        });

        $scope.deleteFiles = function(item){
            alertify.confirm("Storage Operation","确定删除 "+item+" 文件?",
                function(){
                    storageService.deleteFiles($scope.volumnName,item).then(function (ret) {
                        if (ret.data.ret == true) {
                            var _idx = $scope.files.indexOf(item);
                            $scope.files.splice(_idx,1);
                            alertify.success("delete file success");
                        }
                    }, function (ret) {
                        alertify.alert('delete file error', ret.data);
                    });
                },function(){

                }
            );

        }

        $scope.uploadFile = function(){

            var item = {};
            item.name = $scope.volumnName;
            var modalInstance = $uibModal.open({
                animation:true ,
                templateUrl: 'template/cp/uploadFiles.html',
                controller: 'UploadFilesController',
                resolve: {
                    item: function () {
                        return item;
                    }
                }
            });

            modalInstance.result.then(function (ret) {
                if(ret !== undefined){
                    $scope.files.push(ret);
                }
            }, function (err) {
                //dismiss err flow
                if(err !== 'cancel'&& err !== 'backdrop click'  ){
                    alertify.alert('upload error',err);
                }
            });

        }

    }
);